import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateWarehouseDto } from './dto/create-warehouse.dto';
import { UpdateWarehouseDto } from './dto/update-warehouse.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Warehouse } from './entities/warehouse.entity';
import { Not, Repository } from 'typeorm';
import { dateNo } from 'src/utils/fun';
import { Admin } from 'src/admin/entities/admin.entity';

@Injectable()
export class WarehouseService {
  constructor(
      @InjectRepository(Warehouse)
      private readonly warehouseRepository: Repository<Warehouse>,
      ) {}
  async isWarehouseExists(where){
    const result = await this.warehouseRepository.findOne({where});
    return !!result
  }
  async create(createWarehouseDto: CreateWarehouseDto) {
    try{
      let where = {}
      if(createWarehouseDto.id){
        where = {id: Not(createWarehouseDto.id)}
      }
      //验证名称重复
      const isNameExists = await this.isWarehouseExists({
        ...where,
        name: createWarehouseDto.name,
      })
      if(isNameExists){
        throw new HttpException('仓库名称不可重复', HttpStatus.INTERNAL_SERVER_ERROR);
      }
      //保存
      
      const saveData = {
        ...createWarehouseDto,
      }
      // 如果 createWarehouseDto.id 不为真（即新增操作），则添加 number 字段
      if (!createWarehouseDto.id) {
        saveData['code'] = 'CK' + dateNo() + Math.floor(Math.random() * 100).toString().padStart(3, '0')
      }
      //return
      const savedSupplier = await this.warehouseRepository.save(saveData)
      return savedSupplier
    } catch (error) {
      throw new HttpException(error.message, error.status, {
        cause: error
      });
    }
  }

  async findAll(query) {
    try {
      const { page = 1, limit = 20, keyName = ''} = query
      const queryBuilder = this.warehouseRepository
        .createQueryBuilder('warehouse')
        .leftJoinAndSelect(Admin, 'admin', 'admin.id = warehouse.personId')
        .select([
          'warehouse.id AS id',
          'warehouse.name AS name',
          'warehouse.code AS code',
          'warehouse.personId AS personId',
          'warehouse.position AS position',
          'warehouse.remark AS remark',
          'admin.nickname AS createAdminName',
        ])
      if (keyName) {
        queryBuilder.andWhere('name LIKE :keyName OR position LIKE :keyName', { keyName: `%${keyName}%` });
      }
      const warehouse = await queryBuilder
      .offset(Number((page - 1) * limit))
      .limit(Number(limit))
      .getRawMany();
      const total = await queryBuilder
        .getCount();
      return [
        warehouse, total
      ]
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} warehouse`;
  }

  update(id: number, updateWarehouseDto: UpdateWarehouseDto) {
    return `This action updates a #${id} warehouse`;
  }

  async delete(id: string) {
    try {
      return await this.warehouseRepository.delete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async remove(id: string) {
    try {
      return await this.warehouseRepository.softDelete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
